<?php


namespace app\api\controller;


use app\BaseController;
use app\common\model\GoodsBanner;
use app\common\model\GoodsLibraryGoodsRelation;
use app\common\model\GoodsLibraryShopRelation;
use app\common\model\GoodsSku;
use app\common\model\ShopGoods;
use app\common\model\ShopManage;
use Intervention\Image\ImageManager;
use think\facade\Db;
use think\Validate;

class Goods extends BaseController
{
    //商品详情
    public function goodsDetail()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'goods_id|商品id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $goods = \app\common\model\Goods::with(['banner' => function ($query) {
            $query->order('sort', 'desc');
        }, 'sku'])->find($param['goods_id']);
        if (!$goods) {
            return error('商品不存在或已下架');
        }
        foreach ($goods['sku'] as &$v) {
            if (!$v->img) {
                $v->img = $goods->img;
            }
        }
        if ($goods['img_detail'] == '') {
            $goods['img_detail'] = [];
        } else {
            $goods['img_detail'] = explode('|', $goods['img_detail']);
        }
        if($goods['remark'] == ''){
            $goods['remark'] = '[]';
        }
        return success($goods);
    }

    /**
     * 生成商品海报
     */
    public function sharePost()
    {
        $param = $this->request->param();; //接收值
        $validate = new Validate();
        $validate->rule([
            'goods_id|商品id' => 'require|number',
            'path|跳转地址'     => 'require',
            'scene|跳转参数'    => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $goods = \app\common\model\Goods::find($param['goods_id']);
        if (!$goods) {
            return error('商品信息异常');
        }
        $imageManager = new ImageManager();

        //商品海报模板
        $image = $imageManager->make(public_path() . 'poster.png')->resize(660, 961);
        //商品主图
        $product = $imageManager->make($goods->img);
        if ($product->height() > $product->width()) {
            $product = $product->widen(600)->crop(600, 600, 0, (int)(($product->height() - 600) / 2));
        } else {
            $product = $product->heighten(600)->crop(600, 600, (int)(($product->width() - 600) / 2), 0);
        }
//        //如果当前用户是否是团长
//        $userInfo = $this->request->user_info;
//        $scene    = 'test';
//        if ($userInfo->is_head == 1) {
//            $scene = 'invitation_code=' . $userInfo->invitation_code;
//        }
        //第三张是小程序码
        $wechat = new \Wechat();
        $re     = $wechat->getUnlimitQRCode($param['path'], $param['scene']);
        $image3 = $imageManager->make($re)->resize(200, 200);
        //获取用户原型头像
//        $avatar = file_get_contents($userInfo->avatar);
//        $image4 = $imageManager->make(yuanImg($avatar))->resize(90, 90);
//        $image3->insert($image4, 'left-top', 55, 55);

        $image->insert($product, 'left-top', 30, 30);
        $image->insert($image3, 'right-bottom', 29, 58);

        //写入商品信息
        $image->text('积分', 30, 725, function ($font) {
            $font->file(public_path() . 'font/heiya.ttf');
            $font->size(30);
            $font->color('#FF5757');
            $font->valign('left');
        });

        //这个参数是商品价格
//        $price = explode('.', $goods->show_price);
        $price = $goods->show_price;
//        $num   = isset($price[0]) ? $price[0] : '??';
//        $point = isset($price[1]) ? '.' . $price[1] : '';
//        $len   = strlen($num) * 32 + 55;
        $image->text($price, 95, 730, function ($font) {
            $font->file(public_path() . 'font/heiyajiacu.ttf');
            $font->size(50);
            $font->color('#FF5757');
            $font->valign('left');
        });

//        $image->text($point, $len, 730, function ($font) {
//            $font->file(public_path() . 'font/heiya.ttf');
//            $font->size(30);
//            $font->color('#FF5757');
//            $font->valign('left');
//        });

//        $market = (int)$goods->market_price;
//        //划线价格
//        $image->text('￥' . $market, $len + 50, 725, function ($font) {
//            $font->file(public_path() . 'font/heiya.ttf');
//            $font->size(18);
//            $font->color('#A5A5A5');
//            $font->valign('left');
//        });
//        $image->text('———', $len + 50, 725, function ($font) {
//            $font->file(public_path() . 'font/heiya.ttf');
//            $font->size(18);
//            $font->color('#A5A5A5');
//            $font->valign('left');
//        });

        //商品标题
        $title = $goods->name;

        $image->text(mb_substr($title, 0, 14), 35, 785, function ($font) {
            $font->file(public_path() . 'font/heiya.ttf');
            $font->size(30);
            $font->valign('left');
        });

        if (mb_substr($title, 14, 14)) {
            $image->text(mb_substr($title, 14, 14), 35, 830, function ($font) {
                $font->file(public_path() . 'font/heiya.ttf');
                $font->size(30);
                $font->valign('left');
            });
        }
//        //商品标签
//        $flag = $goods->show_flag;
//
//        $image->text(mb_substr($flag, 0, 15), 35, 870, function ($font) {
//            $font->file(public_path() . 'font/heiya.ttf');
//            $font->size(20);
//            $font->color('#999999');
//            $font->valign('left');
//        });
//        $image->save('a.jpg');
        $image         = $image->encode('jpg', 75);
        $base64_encode = 'data:image/jpg;base64,' . base64_encode($image);
        $image->destroy();
        return success(['img_base64' => $base64_encode]);
    }

    /**
     * 上传产品
     *
     */
    public function goodsCreate()
    {
        $param    = $this->request->param(); //接收值
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
            'name|商品名称'    => 'require',
            'price|商品价格'   => 'require',
            //            'content|内容'   => 'require',
            'img|商品图片'     => 'require',
            'stock|库存'     => 'number'
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        //判断权限
        $userId = $this->request->uid;
        if (cache($userId)) {
            return error('请勿重复操作');
        }
        cache($userId, 1, 5);
        $shopId = $param['shop_id'];
        //判断权限
        $a = ShopManage::where('user_id', $userId)
            ->where('shop_id', $shopId)
            ->where('status', 1)
            ->find();
        if (!$a) {
            return error('当前用户没有权限');
        }
        if (!in_array(1, explode(',', $a['function_arr']))) {
            return error('当前用户没有权限');
        }
        $imgDetail = "";
        if (input('img_detail', '')) {
            $imgDetail = implode('|', input('img_detail', ''));
        }
        Db::startTrans();
        try {
            $goods = \app\common\model\Goods::create([
                'name'        => $param['name'],
                'show_price'  => $param['price'],
                'price_low'   => $param['price'],
                'price_high'  => $param['price'],
                'total_stock' => $param['stock'] ?: 100,
                'status'      => 1,
                'shop_id'     => $shopId,
                'content'     => input('content', ''),
                'sku_json'    => json_encode([['name' => '默认', 'value' => ['默认']]], JSON_UNESCAPED_UNICODE),
                'sort'        => 50,
                'img'         => $param['img'][0],
                'img_detail'  => $imgDetail,
                'remark'      => input('remark', ''),
            ]);
            foreach ($param['img'] as &$v) {
                GoodsBanner::create([
                    'goods_id' => $goods->id,
                    'img'      => $v
                ]);
            }
            GoodsSku::create([
                'goods_id'       => $goods->id,
                'original_price' => $param['price'],
                'price'          => $param['price'],
                'stock'          => $param['stock'] ?: 100,
                'img'            => $param['img'][0],
                'sku_json'       => json_encode([['name' => '默认', 'value' => '默认']], JSON_UNESCAPED_UNICODE)
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return error($e->getMessage());
        }
        return success([], '上传成功');

    }

    /**
     * 商品上下架状态修改
     */
    public function goodsIsSaleChange()
    {
        $param    = $this->request->param(); //接收值
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id'  => 'require|number',
            'goods_id|商品id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        //判断权限
        $userId = $this->request->uid;
        $shopId = $param['shop_id'];
        //判断权限
        $a = ShopManage::where('user_id', $userId)->where('shop_id', $shopId)
            ->where('status', 1)->find();
        if (!$a) {
            return error('当前用户没有权限');
        }
        if (!in_array(1, explode(',', $a['function_arr']))) {
            return error('当前用户没有权限');
        }
        $goods = \app\common\model\Goods::where('shop_id', $param['shop_id'])->where('id', $param['goods_id'])->find();
        if ($goods->is_sale == 1) {
            $goods->is_sale = 0;
            $goods->save();
            $msg = "商品下架成功";
        } else {
            $goods->is_sale = 1;
            $goods->save();
            $msg = "商品上架成功";
        }
        return success([], $msg);
    }

    /**
     * 修改产品
     *
     */
    public function goodsUpdate()
    {
        $param    = $this->request->param(); //接收值
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id'  => 'require|number',
            'goods_id|商品id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        //判断权限
        $userId = $this->request->uid;
        $shopId = $param['shop_id'];
        //判断权限
        $a = ShopManage::where('user_id', $userId)->where('shop_id', $shopId)
            ->where('status', 1)->find();
        if (!$a) {
            return error('当前用户没有权限');
        }
        if (!in_array(1, explode(',', $a['function_arr']))) {
            return error('当前用户没有权限');
        }
        Db::startTrans();
        try {
            $goods    = \app\common\model\Goods::find($param['goods_id']);
            $goodsSKu = GoodsSku::where('goods_id', $param['goods_id'])->find();
            if (isset($param['name']) && $param['name']) {
                $goods->name = $param['name'];
            }
            if (isset($param['price']) && $param['price']) {
                $goods->show_price        = $param['price'];
                $goods->price_low         = $param['price'];
                $goods->price_high        = $param['price'];
                $goodsSKu->original_price = $param['price'];
                $goodsSKu->price          = $param['price'];
            }
            if (isset($param['total_stock'])) {
                $goods->total_stock = $param['total_stock'];
                $goodsSKu->stock    = $param['total_stock'];
            }

            if (isset($param['content'])) {
                $goods->content = $param['content'];
            }
            if (isset($param['img']) && $param['img']) {
                $goods->img = $param['img'][0];
                GoodsBanner::where('goods_id', $param['goods_id'])->useSoftDelete('delete_time', time())->delete();
                foreach ($param['img'] as &$v) {
                    GoodsBanner::create([
                        'goods_id' => $param['goods_id'],
                        'img'      => $v
                    ]);
                }
                $goodsSKu->img = $param['img'][0];
            }else{
                GoodsBanner::where('goods_id', $param['goods_id'])->useSoftDelete('delete_time', time())->delete();
            }
            if (isset($param['img_detail']) && $param['img_detail']) {
                $goods->img_detail = implode('|', $param['img_detail']);
            }else{
                $goods->img_detail = '';
            }
            if (isset($param['remark']) && $param['remark']) {
                $goods->remark = $param['remark'];
            }
            $goods->save();
            $goodsSKu->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return error($e->getMessage());
        }
        return success([], '修改成功');

    }

    /**
     * 删除产品
     *
     */
    public function goodsDelete()
    {
        $param    = $this->request->param(); //接收值
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id'  => 'require|number',
            'goods_id|商品id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        //判断权限
        $userId = $this->request->uid;
        $shopId = $param['shop_id'];
        //判断权限
        $a = ShopManage::where('user_id', $userId)->where('shop_id', $shopId)
            ->where('status', 1)->find();
        if (!$a) {
            return error('当前用户没有权限');
        }
        if (!in_array(1, explode(',', $a['function_arr']))) {
            return error('当前用户没有权限');
        }

        $goods    = \app\common\model\Goods::where('id', $param['goods_id'])->useSoftDelete('delete_time', time())->delete();
        $goodsSKu = GoodsSku::where('goods_id', $param['goods_id'])->useSoftDelete('delete_time', time())->delete();

        GoodsBanner::where('goods_id', $param['goods_id'])->useSoftDelete('delete_time', time())->delete();

        return success([], '修改成功');

    }


    /**
     * 商品管理-- 商品库列表
     */
    public function GoodsLibrary()
    {
        $param    = $this->request->param(); //接收值
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shopId = $param['shop_id'];
        $userId = $this->request->uid;
        //判断当前用户是否有权限
        $a = ShopManage::where('user_id', $userId)->where('shop_id', $shopId)
            ->where('status', 1)->find();
        if (!$a) {
            return error('当前用户没有权限');
        }
        if (!in_array(1, explode(',', $a['function_arr']))) {
            return error('当前用户没有权限');
        }
        //查询店铺信息
        $shop = \app\common\model\Shop::find($param['shop_id']);
        if (!$shop) {
            return error('店铺信息异常');
        }
        //获取店铺能获取的商品库
        $library = GoodsLibraryShopRelation::with('goods_library')->where('shop_id', $shopId)->select();
        $list[]  = [
            'id'   => 0,
            'name' => $shop->self_name ?: "自营",
        ];
        if ($shop->share_goods_switch) {
            $list[] = [
                'id'   => 2,
                'name' => $shop->share_name ?: "共享",
            ];
        }
        if ($shop->platform_goods_switch) {
            $list[] = [
                'id'   => 1,
                'name' => $shop->platform_name ?: "工具",
            ];
        }
        foreach ($library as $v) {
            if ($v->goods_library->status == 0) {
                continue;
            }
            if ($v->goods_library_id == 1 || $v->goods_library_id == 2) {
                continue;
            }
            $list[] = [
                'id'   => $v->goods_library_id,
                'name' => $v->goods_library->name
            ];
        }
        return success($list);
    }

    /**
     * 店铺管理 -- 商品库 -- 商品列表
     */
    public function GoodsList()
    {
        $param    = $this->request->param(); //接收值
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id'     => 'require|number',
            'library_id|商品库id' => 'require|number'
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shopId    = $param['shop_id'];
        $userId    = $this->request->uid;
        $libraryId = $param['library_id'];
        [$pageSize, $page] = paginate($param);
        //判断当前用户是否有权限
        $a = ShopManage::where('user_id', $userId)->where('shop_id', $shopId)
            ->where('status', 1)->find();
        if (!$a) {
            return error('当前用户没有权限');
        }
        if (!in_array(1, explode(',', $a['function_arr']))) {
            return error('当前用户没有权限');
        }
        //获取店铺所有商品id
        //自营
        $goodsIdList = \app\common\model\Goods::where('shop_id', $shopId)->column('id');

        //其他库
        $a           = ShopGoods::where('status', 1)->where('shop_id', $shopId)->column('goods_id');
        $goodsIdList = $goodsIdList + $a;
        if ($libraryId == 0) {
            $goods = \app\common\model\Goods::where('shop_id', $shopId)->where('status', 1)
                ->where('id', 'in', $goodsIdList)
                ->order('show_price', 'asc')
                ->limit($page * $pageSize, $pageSize)
                ->select();
        } elseif ($libraryId == 2) { //共享
            //商品库中所有商品id
            $goodsId = GoodsLibraryGoodsRelation::where('goods_library_id', $libraryId)->column('goods_id');
            $goods   = \app\common\model\Goods::where('id', 'in', $goodsId)->where('status', 1)
                ->where('shop_id', '<>', $shopId)
                ->where('is_sale', 1)
                ->order('show_price', 'asc')
                ->limit($page * $pageSize, $pageSize)
                ->select();
            $list = GoodsSku::where('goods_id','in',$goodsId)->group('goods_id')->order('original_price','asc')->column('original_price','goods_id');
            foreach($goods as &$v){
                $v->original_price = isset($list[$v->id]) ? $list[$v->id] : $v->show_price;
            }
        } else {
            //商品库中所有商品id
            $goodsId = GoodsLibraryGoodsRelation::where('goods_library_id', $libraryId)->column('goods_id');
            $goods   = \app\common\model\Goods::where('id', 'in', $goodsId)->where('status', 1)
                ->where('is_sale', 1)
                ->order('show_price', 'asc')
                ->limit($page * $pageSize, $pageSize)
                ->select();
            $list = GoodsSku::where('goods_id','in',$goodsId)->group('goods_id')->order('original_price','asc')->column('original_price','goods_id');
            foreach($goods as &$v){
                $v->original_price = isset($list[$v->id]) ? $list[$v->id] : $v->show_price;
            }
        }

        foreach ($goods as &$v) {
            if (in_array($v->id, $goodsIdList)) {
                $v->is_checked = 1;
            } else {
                $v->is_checked = 0;
            }
        }
//        if ($goods){
//            $goods = $goods->toArray();
//            usort($goods,function($a,$b){
//                if($a['is_checked'] > $b['is_checked']){
//                    return 1;
//                }
//            });
//        }
        return success($goods);
    }

    /**
     * 添加商品进入店铺
     */
    public function addGoodsToShop()
    {
        $param    = $this->request->param(); //接收值
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id'  => 'require|number',
            'goods_id|商品id' => 'require|number'
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shopId  = $param['shop_id'];
        $goodsId = $param['goods_id'];
        $userId  = $this->request->uid;
        //判断当前用户是否有权限
        $a = ShopManage::where('user_id', $userId)->where('shop_id', $shopId)
            ->where('status', 1)->find();
        if (!$a) {
            return error('当前用户没有权限');
        }
        if (!in_array(1, explode(',', $a['function_arr']))) {
            return error('当前用户没有权限');
        }
        //查询商品信息
        $goods = \app\common\model\Goods::find($goodsId);
        if (!$goods) {
            return error('商品信息异常');
        }
        if ($goods->is_sale != 1) {
            return error('商品已下架');
        }
        $shopGoods = ShopGoods::where('shop_id', $shopId)->where('goods_id', $goodsId)->find();
        if (!$shopGoods) {
            ShopGoods::create([
                'shop_id'       => $shopId,
                'goods_id'      => $goodsId,
                'goods_shop_id' => $goods->shop_id
            ]);
            $msg = "添加成功";
        } else {
            if ($shopGoods->status == 1) {
                $shopGoods->status = 0;
                $msg               = "删除成功";
            } else {
                $shopGoods->status = 1;
                $msg               = "添加成功";
            }
            $shopGoods->save();
        }
        return success([], $msg);
    }
}